<?php
$downloads = "/Applications/MAMP/htdocs/crm/crm-ev-dev/apps/attach/";
$safeFilename = '/^\w+\.\w+$/';

if (!isset ($_GET['filename']) )
    menu();
else{
    $filename = $_GET['filename'];
    download();
}

function menu(){
    global $safeFilename, $downloads;
    $uri = $_SERVER['PHP_SELF'];
?>
<html>
<head>
<title>Download Menu</title>
</head>
<body>
<form method="GET" action="<?php echo $uri?>">

    File to download

<?php
    $dir = opendir($downloads);
    if (!$dir) {
        die("Bad downloads setting");
    }
   ?>
   <select name="filename">
     <?php
    while (($file = readdir($dir)) !== false) {
        if (preg_match($safeFilename, $file)) {
            ?><option value="<?php echo $file?>"><?php echo $file?></option>   
<?php
        }
    }
    closedir($dir);
?>
</select>
<input type="submit" name="download" value="Download Selected File">
</form>
</body>
</html>
<?php
}

function download(){
    global $filename, $safeFilename, $downloads;
    // MAKE SURE THE FILENAME IS SAFE!
    if (!preg_match($safeFilename, $filename)) {
        error("Bad filename");
    }
    if (!file_exists("$downloads/$filename")) {
        error("File does not exist");
    }
    header("Content-disposition: attachment; filename=$filename");
    header("Content-type: application/octet-stream");
    readfile("$downloads/$filename");
    exit(0);
}

function error($message) {
?>
    <html>
    <head>
    <title><?php echo $message?></title>
    </head>
    <body>
    <h1><?php echo $message?></h1>
    </body>
    </html>
    <?php
}
?>